package com.muyun.data.modeler.sysadmin.application.service;

import com.muyun.data.modeler.infrastructure.general.consts.MessageConsts;
import com.muyun.data.modeler.infrastructure.general.consts.PatternConsts;
import com.muyun.data.modeler.infrastructure.general.exceptions.TipException;
import com.muyun.data.modeler.infrastructure.general.specs.Entity;
import com.muyun.data.modeler.sysadmin.domain.model.entity.User;
import com.muyun.data.modeler.sysadmin.domain.model.repository.UserRepository;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;

/**
 * 用户管理服务
 *
 * @author muyun12
 * @date 2020-12-20 16:47:21
 * @since 0.1.0
 */
@Service
@Validated
public class UserAdminService {

    private MessageSourceAccessor messageSourceAccessor;
    private UserRepository userRepository;

    /**
     * 新增一个用户
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void createUser(
            @NotBlank(message = "{username}{not.blank}")
            @Length(min = 2, max = 64, message = "{username}{length}")
                    String username,
            @NotBlank(message = "{password}{not.blank}")
            @Length(min = 8, max = 16, message = "{password}{length}")
            @Pattern(regexp = PatternConsts.PASSWORD_REGEX, message = "{password.elements}")
                    String password) {
        User user = new User();
        user.setUsername(username);
        if (userRepository.exists(Example.of(user))) {
            throw new TipException(messageSourceAccessor.getMessage(MessageConsts.CODE_1003));
        }
        userRepository.save(Entity.init(user).encrypt());
    }

    @Autowired
    public void setMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) {
        this.messageSourceAccessor = messageSourceAccessor;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}
